#!/usr/bin/env python3
# _*_coding:utf-8 _*_
__author__ = "Gao"
"""
轮询键盘

10秒内，按下指定字母，测试打字速度
"""

import pygame
import sys
import time
import random

from pygame.locals import *

def print_text(font,x,y,text,color=(255,255,255)):
    imgText = font.render(text,True,color)
    screen.blit(imgText,(x,y))


pygame.init()
screen = pygame.display.set_mode((600,500))

font1 = pygame.font.Font(None,24)
font2 = pygame.font.Font(None,200)

white = 255,255,255
yellow = 255,255,0

key_flag = False
correct_answer = 97    # 字母a
seconds = 11    # 倒计时10秒，为了显示用，加1秒
score = 0
clock_start = 0    # 记录游戏开始的时间
game_over = True


while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        elif event.type == KEYDOWN:    # 按下键盘按键
            key_flag = True
        elif event.type == KEYUP:
            key_flag = False

    keys = pygame.key.get_pressed()    # 遍历所有按键
    if keys[K_ESCAPE]:    # 遍历所有按键，判断指定按键是否被按过
        sys.exit()

    if keys[K_RETURN]:
        if game_over:
            game_over = False
            score = 0    # 重置分数
            seconds = 11    # 重置倒计时
        clock_start = time.clock()    # 游戏开始时间

    current = time.clock() - clock_start
    speed = score * 6    # 换算成每分钟的速度
    if seconds - current < 0:    # 超过10秒后游戏结束
        game_over = True
    elif current <= 10:
        if keys[correct_answer]:
            correct_answer = random.randint(97,122)
            score +=1


    screen.fill((0,100,0))

    print_text(font1,0,0,'Lets see how fast you can type')
    print_text(font1,0,20,'Try to keep up for 10 seconds')

    if key_flag:
        print_text(font1,500,0,'<key>')

    if not game_over:
        print_text(font1,0,80,'Time'+str(int(seconds-current)))

    print_text(font1,0,100,'Speed:'+str(speed)+'letters/min')

    if game_over:
        print_text(font1,0,160,'Press Enter to start...')

    print_text(font2,0,240,chr(correct_answer-32),yellow)

    pygame.display.update()

